package com.inspur.attendance.Controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.inspur.attendance.Service.LoginService;
import com.inspur.attendance.Tools.Operation;
import com.inspur.attendance.Tools.Return;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {

    @Autowired
    LoginService loginService;


    @CrossOrigin
    @PostMapping("/login")
    @Operation
    public Return LoginAuth(@Param("username") String username,
                            @Param("password") String password) {

        Integer flag = loginService.loginAuth(username, password);

        // 1用户信息正确 0用户不存在 2用户密码错误
        switch (flag) {
            case 1:
                String token="";
                String s = new Date().toString();
                token= JWT.create().withAudience(username)
                        .sign(Algorithm.HMAC256(password));
                Map map = new HashMap();
                map.put("token", token);
                map.put("Msg", "登录成功");
                return Return.success(map);
            case 2:
                Map map1 = new HashMap();
                map1.put("Msg", "用户密码错误");
                return Return.success(map1);
            case 0:
                Map map2 = new HashMap();
                map2.put("Msg", "用户不存在");
                return Return.success(map2);
        }
        return null;
    }

}
